<?php defined('SYSPATH') or die('No direct script access.');

class Controller_Works extends Controller_Common {

	public $template='layout/index';

	public function action_index() {
		$per_page = $this->_config->get('works_per_page');
		$year = $this->request->param('year');

		if (!empty($year)) {
			$works = ORM::factory('Works')->getAllYear($this->postfix, $this->getOffset($per_page), $this->request->param('year'));
			$total_items = ORM::factory('Works')->where(DB::expr('YEAR(`creation_date`)'), '=', $this->request->param('year'))->count_all();
		} else {
			$works = ORM::factory('Works')->getAll($this->postfix, $this->getOffset($per_page));
			$total_items = ORM::factory('Works')->count_all();
		}

		if (!empty($works)) {
			$this->buildCarcas();
			$this->template->title = 'Zuber - '.$this->sitetext['our_works']['_value'];
			$this->template->content = View::factory('pages/works', array(
				'works' => $works,
				'dates' => ORM::factory('Works')->getDates(),
				'url' => $this->request->url(),
				'page' => $this->request->param('page'),
				'uri' => $this->request->uri(),
	            'pagination' => Pagination::factory(array(
	            	'view' => 'pagination/basic_'.$this->lang,
	                'total_items' => $total_items,
	                'items_per_page' => $this->_config->get('works_per_page', $this->request->param('id')),
	            ))
			));
		} else {
			throw new HTTP_Exception_404(':page does not exist', array(':page' => 'Gaia'));
		}
	}

	public function action_one() {
		$work = ORM::factory('Works')->getOne($this->postfix, $this->request->param('id'));

		if (!empty($work)) {
			$this->buildCarcas();
			$this->template->title = 'Zuber - '.$this->sitetext['our_works']['_value'].' - '.$work->title;
			$this->template->description = $work->meta_description;
			$this->template->content = View::factory('pages/oneWork', array(
				'work' => $work,
				'team' => DB::select('team.id', 'sort', array('fio'.$this->postfix, 'fio'), array('post'.$this->postfix, 'post'), 'image')->from('works_has_many_team')->where('works_has_many_team.works_id', '=', $work->id)->join('team', 'LEFT')->on('works_has_many_team.team_id', '=', 'team.id')->order_by('sort', 'DESC')->as_object()->execute(),
				'says' => ORM::factory('Says')->getAll($this->postfix, $this->request->param('id'))
			));
		} else {
			throw new HTTP_Exception_404(':page does not exist', array(':page' => 'Gaia'));
		}
	}
}